import Vue from 'vue'
import Vuex from 'vuex'


const USER_LOGIN = 'USER_LOGIN'
const USER_LOGOUT = 'USER_LOGOUT'

const state = JSON.parse(sessionStorage.getItem('user')) || {}

const actions = {
  [USER_LOGIN]({ commit }, payload) {
    sessionStorage.setItem('user', JSON.stringify(payload.user))
    commit(USER_LOGIN, payload.user)
  },
  [USER_LOGOUT]({ commit }) {
    sessionStorage.removeItem('user')
    commit(USER_LOGOUT)
  },
}

const mutations = {
  [USER_LOGIN](state, payload) {
    Vue.set(state, 'user', payload.user)
    Vue.set(state, 'expire', payload.expire)
    Vue.set(state, 'token', payload.token)
  },
  [USER_LOGOUT](state) {
    Object.keys(state).forEach(key => Vue.delete(state, key))
  },
}

export default {
  state,
  actions,
  mutations,
}
